import { warn } from 'vue'
import { cloneDeep, merge } from 'lodash-es'
import { routerBeforeEach } from '@/utils/router/interceptor'
import { useRouterStore } from '@/store/router.js'

const NAVIGATE_TYPE = {
  NAVIGATE_TO: 'navigateTo',
  REDIRECT_TO: 'redirectTo',
  RE_LAUNCH: 'reLaunch',
  SWITCH_TAB: 'switchTab',
  NAVIGATE_BACK: 'navigateBack'
}

const filterPath = (url, prefix = '') => {
  const path = url.split('?')[0]
  return prefix + (path.startsWith('/') ? path.substring(1) : path)
}

export class Navigates {
  constructor (type, options) {
    this.type = type || NAVIGATE_TYPE.NAVIGATE_TO
    this.options = options || {}
  }

  navigate (url, options) {
    const navigateOptions = merge(cloneDeep(this.options), options)
    const _options = merge({ url }, navigateOptions)
    switch (this.type) {
      case NAVIGATE_TYPE.NAVIGATE_TO:
        uni.navigateTo(_options)
        break
      case NAVIGATE_TYPE.REDIRECT_TO:
        uni.redirectTo(_options)
        break
      case NAVIGATE_TYPE.RE_LAUNCH:
        uni.reLaunch(_options)
        break
      case NAVIGATE_TYPE.SWITCH_TAB:
        uni.switchTab(_options)
        break
      case NAVIGATE_TYPE.NAVIGATE_BACK:
        uni.navigateBack(navigateOptions)
        break
      default:
        warn('navigate Error')
        break
    }
  }

  /**
     * uni.navigateTo
     * @param url
     * @param options
     */
  push (url, options) {
    this.type = NAVIGATE_TYPE.NAVIGATE_TO
    this.navigate(url, options)
  }

  /**
     * uni.redirectTo
     * @param url
     * @param options
     */
  replace (url, options) {
    this.type = NAVIGATE_TYPE.REDIRECT_TO
    this.navigate(url, options)
  }

  /**
     * uni.reLaunch
     * @param url
     * @param options
     */
  replaceAll (url, options) {
    this.type = NAVIGATE_TYPE.RE_LAUNCH
    this.navigate(url, options)
  }

  /**
     * uni.switchTab
     * @param url
     * @param options
     */
  pushTab (url, options) {
    // 微信小程序端uni.switchTab拦截无效处理
    /* #ifdef MP-WEIXIN */
    if (!routerBeforeEach(url)) {
      return
    }
    /* #endif */
    this.type = NAVIGATE_TYPE.SWITCH_TAB
    this.navigate(url, options)
  }

  /**
     * uni.navigateBack
     * @param options
     */
  back (options) {
    this.type = NAVIGATE_TYPE.NAVIGATE_BACK
    this.navigate('', options)
  }

  /**
     * 自动判断跳转页面 (navigateTo|switchTab)
     * @param url
     * @param options
     */
  go (url, options) {
    const path = filterPath(url)
    const routerStore = useRouterStore()
    const routes = routerStore.getRoutes
    const route = routes.get(path)
    if (route.meta.tabBar) {
      this.pushTab(url, options)
      return
    }
    if (options.replace) {
      this.replace(url, options)
      return
    }
    this.push(url, options)
  }
}
